var UserChatmsg = app.controller('UserChatmsg', function($stateParams,$rootScope, $scope,$window, $http,$cordovaCamera,
		$cordovaFileTransfer,$cordovaProgress,$interval,$cordovaDatePicker,$cordovaChat,$timeout,$state,$cordovaKeyboard,UserChatmsgData) {

	$rootScope.showf=false;	
	$scope.msg = "";
	$scope.queue=[];
	$scope.espression=[];
	$scope.queuechange = true;
	$rootScope.title = '消息';

	$scope.busy = false;
	$scope.currentPage = 1;
	$scope.limit = 10;
	$scope.pages = 1;

	$rootScope.fu={"user_id":0,"headimgurl":"","real_name":"","gender":0};
	$scope.m={"user_id":0,"real_name":0,"headimgurl":"","gender":0};

	$scope.em="";
	$scope.express = function(e) {
		$scope.em=e;
		$scope.add();
	}

	$scope.order={};
	var cid=$stateParams.cid;
	var url=SITE_URL+"index.php?app=baseloginapp&act=orderinfo&callback=JSON_CALLBACK&id="+cid;
	$http.jsonp(url).success( function(data) {
		if(data.done){
			$scope.o=data.retval;
		}
	});
	var id=$stateParams.id;
	var url=SITE_URL+"index.php?app=baseloginapp&act=msguser&callback=JSON_CALLBACK&id="+id;
	$http.jsonp(url).success( function(data) {
		if(data.done){
			$rootScope.fu=data.retval.fu;
			$scope.m=data.retval.m;

			$rootScope.title=$rootScope.fu.real_name;

			var name =$rootScope.fu.real_name;
			var head =$rootScope.fu.headimgurl;

			var real_name=$scope.m.real_name;
			var headimgurl=$scope.m.headimgurl;

			url=SITE_URL+"index.php?app=usersnsapp&callback=JSON_CALLBACK&act=allespression";
			$http.jsonp(url).success( function(data) {
				$rootScope.alle = data.retval;

				url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=chatmsg&id="+id+"&cid="+cid;
				$http.jsonp(url).success( function(data) {
					data=data.retval.data;
					if(data.length>0){
						var t1="";
						for(var i=$scope.queue.length-1;i>=0;i--){
							t1=$scope.queue[i].add_time;
							if(t1!=""){
								break;
							}
						}
						for(var i=0;i<data.length;i++){
							if(data[i]!=undefined){
								if(data[i].fromuser==$scope.m.user_id){
									data[i].fromname=real_name;
									data[i].fromimg=headimgurl;
								}else{
									data[i].fromname=name;
									data[i].fromimg=head;
								}
								var t=data[i].add_time;
								if(t1!=""){
									var d=new Date(t);
									var d1=new Date(t1);
									var d2=d.getTime()-d1.getTime();
									if(d2/1000<=60&&data.length!=i+1){
										data[i].add_time="";
									}
									else{
										t1=data[i].add_time;
									}
								}
								else{
									t1=data[i].add_time;
								}
								var msgda=data[i].msg;

								var p = /\[.*?\]/g;
								var m = msgda.match(p);
								if(m!=undefined&&m.length>0){
									for(var j=0;j<m.length;j++){
										for(var facei=0;facei<$rootScope.alle.length;facei++){
											if($rootScope.alle[facei].d_key==m[j]){
												msgda=msgda.replace(m[j], "<img src='"+$rootScope.localurl+$rootScope.alle[facei].d_value+"' width='30'/>");
											}
										}
									}
								}
								data[i].msg=msgda;
								data[i].playf="video.png";
								data[i].playm="videor.png";
								$scope.queue.insert(0,data[i]);
							}
						}
					}							
				});
			});
		}
	});

	var url=SITE_URL+"index.php?app=usersnsapp&callback=JSON_CALLBACK&act=espression";
	$http.jsonp(url).success(function(data) {
		$scope.espression=data.retval;
	});

	$scope.openLightboxModal = function (s) {
		var imagesurl = $rootScope.site+n.msg;
		photoview(0,imagesurl)
	};

	$scope.add = function() {
		$rootScope.$broadcast('add',$scope.em);
	}

	$scope.remove = function() {
		$rootScope.$broadcast('remove');
	}

	$("body").scrollTop($(document).height());
	$(".message_mask").height($(document).height());
	$scope.$watch('queuechange', function(newValue, oldValue) {
		$timeout(function(){
			$("body").scrollTop($(document).height());
			$(".message_mask").height($(document).height());
		});
	});

	$scope.msgfocus=false;
	$scope.$watch('msgfocus', function(newValue, oldValue) {
		try{
			if(newValue){
				$cordovaKeyboard.show();
				$timeout(function(){
					$("#msgtxt").focus();
				},600);
			}
		}
		catch(e){showcatch(e);}
	});

	$scope.is_show = 0;
	$scope.biaoqing = function(){
		$scope.is_show = !$scope.is_show;
		if($scope.is_show){
			try{
				$cordovaKeyboard.close();
			}
			catch(e){showcatch(e);}
		}
		$(".message_mask").height($(document).height());
	}


	$rootScope.media;
	$scope.sindex=0;
	$scope.play = function(s){
		try{
			var n=s.q;
			if(n.msgtype==1){
				//播放音频 m 即为音频地址
				if($rootScope.media!=undefined&&$rootScope.media!=null){
					if(n.fromuser==$scope.m.user_id){
						$scope.queue[$scope.sindex].playm="videor.png";
					}
					else{
						$scope.queue[$scope.sindex].playf="video.png";
					}
					$rootScope.media.release();
					/*
					$rootScope.media.stop();
					if(n.fromuser==$scope.m.user_id){
						$scope.queue[$scope.sindex].playm="videor.png";
					}
					else{
						$scope.queue[$scope.sindex].playf="video.png";
					}
					console.log('replay png');
					console.log($scope.queue[$scope.sindex].playm);
					console.log($scope.queue[$scope.sindex].playf);
					$rootScope.media.src=$rootScope.site+n.msg;
					console.log('replay');
					console.log($rootScope.media.src);
					$scope.sindex=s.$index;
					if(n.fromuser==$scope.m.user_id){
						$scope.queue[$scope.sindex].playm="yellow_d.gif";
					}
					else{
						$scope.queue[$scope.sindex].playf="write_d.gif";
					}
					console.log('replay gif');
					console.log($scope.queue[$scope.sindex].playm);
					console.log($scope.queue[$scope.sindex].playf);
					$rootScope.media.play();*/
				}
				//else
				{

					$rootScope.media=audioplay($rootScope.site+n.msg);
					console.log('newplay');
					console.log($rootScope.media.src);
					$rootScope.media.successCallback=function(){
						if(n.fromuser==$scope.m.user_id){
							$scope.queue[$scope.sindex].playm="videor.png";
						}
						else{
							$scope.queue[$scope.sindex].playf="video.png";
						}
						console.log('successCallback png');
						console.log($scope.queue[$scope.sindex].playm);
						console.log($scope.queue[$scope.sindex].playf);
						$scope.$apply();
					};
					$rootScope.media.errorCallback=function(err){
						if(n.fromuser==$scope.m.user_id){
							$scope.queue[$scope.sindex].playm="videor_err.png";
						}
						else{
							$scope.queue[$scope.sindex].playf="video_err.png";
						}
						console.log(err);
						console.log('errorCallback png');
						console.log($scope.queue[$scope.sindex].playm);
						console.log($scope.queue[$scope.sindex].playf);
						$scope.$apply();
					};
					$scope.sindex=s.$index;
					if(n.fromuser==$scope.m.user_id){
						$scope.queue[$scope.sindex].playm="yellow_d.gif";
					}
					else{
						$scope.queue[$scope.sindex].playf="write_d.gif";
					}
					console.log('newplay png');
					console.log($scope.queue[$scope.sindex].playm);
					console.log($scope.queue[$scope.sindex].playf);
					$rootScope.media.play();
				}
			}
		}
		catch(e){
			console.log('play');
			console.log(e);
		}
	}

	$rootScope.$$listeners['$cordovaChat:ChatMessageReciveShowEvent'] = [];
	$rootScope.$on('$cordovaChat:ChatMessageReciveShowEvent', function(event, msg){
		console.log('msg');
		console.log(msg);
		if(msg.fromuser==$rootScope.fu.user_id||msg.fromuser==$scope.m.user_id){
			
			if(msg.fromuser==$rootScope.fu.user_id){
				//更新已读状态
				if($scope.o!=null&&$scope.o.consult_tid!=null&&$scope.o.consult_tid!=0){
					var url=SITE_URL+"index.php?app=baseloginapp&act=updatemsg&callback=JSON_CALLBACK&id="+$scope.o.consult_tid;
					$http.jsonp(url).success( function(data) {
						if(data.done){
						}
					});
				}
			}
			
			
			if($scope.queue.length>0){
				var t=msg.add_time;
				var t1="";
				for(var i=$scope.queue.length-1;i>=0;i--){
					t1=$scope.queue[i].add_time;
					if(t1!=""){
						break;
					}
				}
				if(t1!=""){
					var d=new Date(t);
					var d1=new Date(t1);
					var d2=d.getTime()-d1.getTime();
					if(d2/1000<=60){
						msg.add_time="";
					}
				}
			}
			try {
				var p = /\[.*?\]/g;
				var m = msg.msg.match(p);
				if (m != undefined && m.length > 0) {
					for (var j = 0; j < m.length; j++) {
						for (var i = 0; i < $rootScope.alle.length; i++) {
							if ($rootScope.alle[i].d_key == m[j]) {
								msg.msg = msg.msg.replace(m[j], "<img src='" + $rootScope.localurl + $rootScope.alle[i].d_value + "' width='30'/>");
							}
						}
					}
				}
			}catch (e){
				showcatch(e);
			}

			msg.playf="video.png";
			msg.playm="videor.png";

			if(msg.fromuser==$rootScope.fu.user_id){
				msg.fromname=$rootScope.fu.real_name;
				msg.fromimg=$rootScope.fu.headimgurl;
			}else{
				msg.fromname=$scope.m.real_name;
				msg.fromimg=$scope.m.headimgurl;
			}

			$scope.queue.push(msg);
			console.log('showmessage')
			$scope.queuechange=!$scope.queuechange;
			if(msg.fromuser==$rootScope.fu.user_id){
				try{
					$scope.$apply();
				}
				catch(e){}
			}
			else{
				$scope.msg="";
				if($scope.is_show==0&&$scope.v == false&&msg.magtype==0)
					$scope.msgfocus=!$scope.msgfocus;
			}
			//$("body").scrollTop($(document).height());
		}

		if(!$rootScope.inback){
			//$cordovaChat.ChatFriendClearNew($rootScope.fu.user_id);
		}
	});
	$scope.v = false;
	$scope.v_start = 0;
	$scope.v_move = 0;


	//录音
	$scope.video_click = function(){
		try{

			if($scope.v_start == 1){
				return false;
			}
			$scope.is_show=0;

			$scope.v = !$scope.v;

			$(".message_mask").height($(document).height());
			$cordovaKeyboard.close();
		}
		catch(e){showcatch(e);}
	}

	$scope.getfocus = function(s){
		$(s).addClass("getfocus");
	}

	$scope.lostfocus = function(s){
		$(s).addClass("getfocus");
	}
	$rootScope.type = '默认';
	//表情tab
	$scope.express_type = function(type) {
		$rootScope.type = type;
	}

	$scope.nulldata=false;
	
	//滚动条顶部事件
	/*window.onscroll = function(){
		var t = document.documentElement.scrollTop || document.body.scrollTop;
		if(t==0&&!$scope.nulldata&&$rootScope.xstopscroll){

			$scope.loadMore();
		}
	}*/
	
	$("#viewbd").scroll(function() {
		if($(this).scrollTop()==0){
			$scope.loadMore();
		}
	});

	$scope.nomore=false;
	$scope.loadMore = function() {
		try{
			if ($scope.busy) {
				return false;
			}
			var name =$rootScope.fu.real_name;
			var head =$rootScope.fu.headimgurl;

			var real_name=$scope.m.real_name;
			var headimgurl=$scope.m.headimgurl;

			$scope.busy = true;
			$scope.currentPage++;
			url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=chatmsg&id="+id+"&cid="+cid+"&page="+$scope.currentPage;
			$http.jsonp(url).success( function(data) {
				data=data.retval.data;
				if(data.length>0){
					var t1="";
					for(var i=$scope.queue.length-1;i>=0;i--){
						t1=$scope.queue[i].add_time;
						if(t1!=""){
							break;
						}
					}
					for(var i=0;i<data.length;i++){
						if(data[i]!=undefined){
							if(data[i].fromuser==$scope.m.user_id){
								data[i].fromname=real_name;
								data[i].fromimg=headimgurl;
							}else{
								data[i].fromname=name;
								data[i].fromimg=head;
							}
							var t=data[i].add_time;
							if(t1!=""){
								var d=new Date(t);
								var d1=new Date(t1);
								var d2=d.getTime()-d1.getTime();
								if(d2/1000<=60&&data.length!=i+1){
									data[i].add_time="";
								}
								else{
									t1=data[i].add_time;
								}
							}
							else{
								t1=data[i].add_time;
							}
							var msgda=data[i].msg;

							var p = /\[.*?\]/g;
							var m = msgda.match(p);
							if(m!=undefined&&m.length>0){
								for(var j=0;j<m.length;j++){
									for(var facei=0;facei<$rootScope.alle.length;facei++){
										if($rootScope.alle[facei].d_key==m[j]){
											msgda=msgda.replace(m[j], "<img src='"+$rootScope.localurl+$rootScope.alle[facei].d_value+"' width='30'/>");
										}
									}
								}
							}
							data[i].msg=msgda;
							data[i].playf="video.png";
							data[i].playm="videor.png";
							$scope.queue.insert(0,data[i]);
						}
					}
					$scope.busy=false;
				}else{
					$scope.currentPage--;
					$scope.nomore=true;
				}	
			});
		}catch(e){showcatch(e);$scope.busy=false;$scope.currentPage--;}
	};
	$rootScope.$$listeners['$cordovaKeyboard:show'] = [];
	$rootScope.$on('$cordovaKeyboard:show', function(event, msg){
		$timeout(function(){
			$("body").scrollTop($(document).height());
			$(".message_mask").height($(document).height());
			$("#msgtxt").focus();
		});
		$scope.is_show=0;
	});
	$scope.msgclick=function(){
		$scope.is_show=0;
		$(".message_mask").height($(document).height());
		$scope.msgfocus=!$scope.msgfocus;
	};

	/*
	$rootScope.$on('$cordovaKeyboard:show', function(event, msg){
		$scope.is_show=false;
	});
	 */
	$rootScope.pic=[];
	$rootScope.item_id=1;
	$rootScope.file_id=0;
	$rootScope.maxpic=9;

	if(window.device){
		var pv = ProgressIndicator;
	}
	else{
		var pv = undefined;
	}
	var fileresulti=0;
	$scope.uppicture = function(filedata,filepath){
		try{
			if(fileresulti>=filepath.length){
				pv.hide();
				return false;
			}
			if(filedata.done){
				console.log('$cordovaFileTransfer.upstart ',filepath[fileresulti]);
				pv.show('正在上传 ...','HORIZONTAL',"HOLO_DARK");
				pv.setProgress(0);

				var imageURI=filepath[fileresulti];
				$rootScope.ECM_ID=filedata.retval.userid;
				$rootScope.HTTP_USER_AGENT = filedata.retval.HTTP_USER_AGENT;

				var uri = $rootScope.site+'index.php?app=appupload&ajax=ajax&XDEBUG_SESSION_START=ECLIPSE_DBGP';

				var options = new FileUploadOptions();
				options.fileKey="file";
				options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
				options.mimeType="text/plain";

				var params = {};
				params.ECM_ID = $rootScope.ECM_ID;
				params.HTTP_USER_AGENT = $rootScope.HTTP_USER_AGENT;
				params.belong = 10;
				params.item_id = 1;
				options.params = params;

				$cordovaFileTransfer.upload(uri,imageURI,options).then(function (r) {
					console.log('$cordovaFileTransfer.sucess ',r);

					data = JSON.parse(r.response);
					if(data.done){
						$rootScope.pic.push(data.retval);
						$scope.imagesend(data.retval.file_path);
						//alert(JSON.stringify(sender.pic));
					}
					else{
						showtoast(data.msg);
					}
					fileresulti++;
					$scope.uppicture(filedata,filepath);
				}, function (error) {
					console.log('$cordovaFileTransfer.error ',error);
					showtoast('图片选择失败'+error);
					fileresulti++;
					$scope.uppicture(filedata,filepath);
				}, function(progressEvent) {
					if (progressEvent.lengthComputable) {
						//loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
						//$cordovaProgress.showBarWithLabel(true, 100000, '正在上传图片');

					} else {
						//$cordovaProgress.showBarWithLabel(true, 100000, '正在上传图片');
						//loadingStatus.increment();
					}
					pv.setProgress(progressEvent.loaded / progressEvent.total);
				});
			}
		}
		catch(e){
			pv.hide();
			showcatch(e);
		}
	}

	$scope.getpicture = function(){
		$scope.is_show=0;
		$(".message_mask").height($(document).height());
		try{
			$cordovaKeyboard.close();
		}
		catch(e){showcatch(e);}
		$scope.mediaFile = null;
		$scope.absfilepath=null;
		$.DIC.dialog({
			content:"请选择",
			okValue:'本地图库',
			cancelValue:'我要拍照',
			isMask:true,
			ok:function (){

				window.imagePicker.getPictures(
						function(results) {
							fileresulti=0;
							var url=$rootScope.site+"index.php?app=usermyapp&act=upfile&callback=JSON_CALLBACK";

							$http.jsonp(url).success( function(data) {
								console.log(data);
								if(data.done){
									$scope.uppicture(data,results);
								}
							});
						}, function (error) {
							console.log('Error: ' + error);
						}, {
							maximumImagesCount: $rootScope.maxpic-$rootScope.pic.length,
							width: 400
						}
				);
			},
			cancel:function(){
				$cordovaCamera.getPicture({ quality: 50,
					destinationType: Camera.DestinationType.FILE_URI,
					targetWidth: 400,
					targetHeight: 400,
					//allowEdit:true,
					sourceType:1,
					Direction:1
				}).then(function (imageURI) {
					console.log(imageURI);

					url=$rootScope.site+"index.php?app=usermyapp&act=upfile&callback=JSON_CALLBACK";
					$http.jsonp(url).success( function(data) {
						console.log(data);
						if(data.done){
							$rootScope.ECM_ID=data.retval.userid;
							$rootScope.HTTP_USER_AGENT = data.retval.HTTP_USER_AGENT;
							var uri = $rootScope.site+'index.php?app=appupload&ajax=ajax&XDEBUG_SESSION_START=ECLIPSE_DBGP';
							console.log(uri);
							var options = new FileUploadOptions();
							options.fileKey="file";
							options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
							options.mimeType="text/plain";
							var params = {};
							params.ECM_ID = $rootScope.ECM_ID;
							params.HTTP_USER_AGENT = $rootScope.HTTP_USER_AGENT;
							params.belong = 12;
							params.item_id = 1;
							options.params = params;
							ProgressIndicator.showProgressBar('正在发送...');
							$cordovaFileTransfer.upload(uri,imageURI,options).then(function (r) {
								console.log("Code = " + r.responseCode);
								console.log("Response = " + r.response);
								console.log("Sent = " + r.bytesSent);
								ProgressIndicator.hide();
								data = JSON.parse(r.response);
								if(data.done){
									//$scope.s.store_logo=data.retval.file_path;
									$scope.imagesend(data.retval.file_path);
								}
								else{
									showtoast(data.msg);
								}
							}, function (error) {
								console.log("An error has occurred: Code = " + error.code);
								console.log("upload error source " + error.source);
								console.log("upload error target " + error.target);
								ProgressIndicator.hide();
								showtoast('图片选择失败，'+error);
							}, function(progressEvent) {
								ProgressIndicator.setProgress(progressEvent.loaded / progressEvent.total);
							});
						}
					});
				});
			}
		});
	}

	$scope.beforesend=function(){
		/*if(!$cordovaChat.ChatConnected()&&window.localStorage.user!=undefined&&window.localStorage.user!=null&&window.localStorage.user!=""){
			var d=JSON.parse(window.localStorage.user);
			$cordovaChat.init(d.BOSH_SERVICE,d.CHATURI,d.CHATUSER,d.CHATUSERP);
			$cordovaChat.ChatConnect();
		}*/
	}

	$scope.imagesend = function(imagepath){
		$scope.beforesend();
		var type=0;
		if($rootScope.fu.store_id>0){
			type=1;
		}
		$cordovaChat.ChatSendMessage($rootScope.fu.user_id,imagepath,$scope.m.real_name,$scope.m.headimgurl,type,$rootScope.fu.real_name,$rootScope.fu.headimgurl,2,0,$scope.m.gender,$rootScope.fu.gender).then(function(success){

		},function(error){
			showtoast(error);
		});
	}

	$scope.send = function(){
		$scope.beforesend();
		if($scope.msg==""){
			showtoast("请输入内容");
			return;
		}

		var type=0;
		if($rootScope.fu.store_id>0){
			type=1;
		}

		var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=writechatmsg&id="+$rootScope.fu.user_id+"&msg="+$scope.msg+"&cid="+cid;;
		$http.jsonp(url,{ignoreLoadingBar:true}).success(function(data){
			//$rootScope.orthermsg(data.retval.push);
		});

		$cordovaChat.ChatSendMessage($rootScope.fu.user_id,$scope.msg,$scope.m.real_name,$scope.m.headimgurl,type,$rootScope.fu.real_name,
				$rootScope.fu.headimgurl,0,0,$scope.m.gender,$rootScope.fu.gender,cid).then(function(success){
				},function(error){
					showtoast(error);
				});
	}

	$scope.itemOnLongPress = function() {
		$scope.audiostart();
	}

	$scope.itemOnTouchEnd = function() {
		$scope.audiostop();
	}

	$scope.itemOnTouchMove = function() {
		$scope.audioclear();
	}
	$scope.audiosend = function(audiomsg,msglengthapp){
		$scope.beforesend();
		var type=0;
		if($rootScope.fu.store_id>0){
			type=1;
		}

		var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=writechatmsg&id="+$rootScope.fu.user_id+"&msg="+audiomsg+"&t=1&l="+msglengthapp+"&cid="+cid;
		$http.jsonp(url,{ignoreLoadingBar:true}).success(function(data){
			//$rootScope.orthermsg(data.retval.push);
		});

		$cordovaChat.ChatSendMessage($rootScope.fu.user_id,audiomsg,$scope.m.real_name,$scope.m.headimgurl,type,$rootScope.fu.real_name,
				$rootScope.fu.headimgurl,1,msglengthapp,$scope.m.gender,$rootScope.fu.gender,cid).then(function(success){

				},function(error){
					showtoast(error);
				});
	}

	$scope.d = 0;
	$scope.timer=null;
	$scope.ms=0;
	$scope.ss=0;
	$scope.audiostart=function(){
		try{
			$scope.ms=0;
			$scope.ss=0;
			$scope.v_start = 1;
			$scope.v_move=0;
			$scope.d = 0;
			if($scope.timer!=null)
				$interval.cancel($scope.timer);
			$scope.timer =  $interval(function(){			
				if($scope.v_start != 0){
					$scope.d++;
					$scope.ms=parseInt($scope.d/60);
					$scope.ss=parseInt($scope.d%60);
				}else{
					//$scope.o.status =$scope.ostatus;
					$interval.cancel($scope.timer);
				}
			},1000);
			console.log('start');
			window.plugins.audioRecorderAPI.record(function(msg) {
				// complete
				console.log('record ok: ' + msg);
			}, function(msg) {
				// failed
				console.log('record err'+msg);
			}, 600); // record 30 seconds
		}
		catch(e){showcatch(e);}
	};

	$scope.audioclear=function(){
		try{
			$scope.v_start = 0;
			$scope.v_move=0;
			$scope.d = 0;
			$scope.ms=0;
			$scope.ss=0;
			if($scope.timer!=null)
				$interval.cancel($scope.timer);
			console.log('clear');
		}
		catch(e){showcatch(e);}
	};
	$scope.audiostop=function(){
		try{
			$scope.v_start = 0;
			$scope.v_move=0;
			if($scope.timer!=null)
				$interval.cancel($scope.timer);
			console.log('end');
			window.plugins.audioRecorderAPI.stop(function(audiopath) {
				// success
				console.log('ok: ' + audiopath);
				if($rootScope.isf){
					$rootScope.isf=false;
					return false;
				}

				if($scope.d<3){
					showtoast('录音时间太短');
					return false;
				}
//				上传
				msglengthapp=0;
				url=$rootScope.site+"index.php?app=usermyapp&act=upfile&callback=JSON_CALLBACK";
				$http.jsonp(url).success( function(data) {
					console.log(data);
					if(data.done){
						$rootScope.ECM_ID=data.retval.userid;
						$rootScope.HTTP_USER_AGENT = data.retval.HTTP_USER_AGENT;
						var uri = $rootScope.site+'index.php?app=appuploadvideo&ajax=ajax&XDEBUG_SESSION_START=ECLIPSE_DBGP';
						console.log(uri);
						var options = new FileUploadOptions();
						options.fileKey="file";
						options.fileName=audiopath.substr(audiopath.lastIndexOf('/')+1);
						options.mimeType="text/plain";
						var params = {};
						params.ECM_ID = $rootScope.ECM_ID;
						params.HTTP_USER_AGENT = $rootScope.HTTP_USER_AGENT;
						params.belong = 10;
						params.item_id = JSON.parse(window.localStorage.user).CHATUSER;;
						options.params = params;
						ProgressIndicator.showProgressBar('正在发送...');
						$cordovaFileTransfer.upload(uri,audiopath,options).then(function (r) {
							console.log("Code = " + r.responseCode);
							console.log("Response = " + r.response);
							console.log("Sent = " + r.bytesSent);
							ProgressIndicator.hide();
							//alert(r.response);
							data = JSON.parse(r.response);
							if(data.done){
								$scope.audiosend(data.retval.file_path,$scope.d);
								$scope.d = 0;
								$scope.v_start = 0;
							}
							else{
								showtoast(data.msg);
							}
						}, function (error) {
							console.log("An error has occurred: Code = " + error.code);
							console.log("upload error source " + error.source);
							console.log("upload error target " + error.target);
							ProgressIndicator.hide();
							showtoast('发送失败，'+error);
						}, function(progressEvent) {
							ProgressIndicator.setProgress(progressEvent.loaded / progressEvent.total);
						});
					}
				});
			}, function(msg) {
				// failed
				//alert('ko: ' + msg);
				console.log('stop err'+msg);
			});
		}
		catch(e){showcatch(e);}
	};

	if($rootScope.isf){
		$scope.audiostart();
		setTimeout(function () {
			$scope.audiostop();
		}, 500);
	}

});
UserChatmsg.UserChatmsgData=function($q, $http,$stateParams,$rootScope){
	try {
		var data = [];
		var def = $q.defer();
		if(window.localStorage.u==undefined||window.localStorage.u==null||window.localStorage.u==""){			
			$rootScope.go("loginmain");
		}else{
			def.resolve(data);
		}

		return def.promise;
	} catch (e) {
		showcatch(e);
	}
}